package wsepForum.ui.swing.innerPanels;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ExecutionException;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.MatteBorder;

import wsepForum.domain.exceptions.SystemFailureException;
import wsepForum.domain.exceptions.UnAuthorizedException;
import wsepForum.domain.exceptions.WrongPasswordException;
import wsepForum.network.common.GUIAnswer;
import wsepForum.network.common.GUIAnswer.AnswerType;
import wsepForum.network.common.GUIRequest.RequestType;
import wsepForum.persistance.exceptions.WrongUserNameException;
import wsepForum.ui.swing.SetSwitcher.SetType;
import wsepForum.ui.swing.outerPanels.AOuterPanel;
import wsepForum.ui.swing.workers.ForumWorker;

public class RegisterPanel extends AInnerPanel {
	private static final long serialVersionUID = -3611214291656971195L;

	/**
	 * Create the panel.
	 */
	public RegisterPanel(AOuterPanel oPanel) {
		super(oPanel);
		final JTextField userNameField;
		final JTextField passwordField;
		final JTextField passwordAgainField;

		setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
		setLayout(null);
		setBackground(new Color(230, 230, 250));
		setBounds(20, 93, 716, 364);

		JLabel lblRegister = new JLabel("Register\r\n");
		lblRegister.setHorizontalAlignment(SwingConstants.CENTER);
		lblRegister.setFont(new Font("Cooper Black", Font.PLAIN, 18));
		lblRegister.setBounds(290, 11, 136, 41);
		add(lblRegister);

		JLabel lblUserName = new JLabel("User Name:");
		lblUserName.setHorizontalAlignment(SwingConstants.RIGHT);
		lblUserName.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblUserName.setBounds(191, 96, 75, 22);
		add(lblUserName);

		JLabel lblPassword = new JLabel("Password:");
		lblPassword.setHorizontalAlignment(SwingConstants.RIGHT);
		lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblPassword.setBounds(191, 129, 75, 22);
		add(lblPassword);

		JLabel lblPasswordAgain = new JLabel("Password again:");
		lblPasswordAgain.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblPasswordAgain.setHorizontalAlignment(SwingConstants.RIGHT);
		lblPasswordAgain.setBounds(171, 162, 95, 22);
		add(lblPasswordAgain);

		userNameField = new JTextField();
		userNameField.setBounds(276, 98, 177, 20);
		add(userNameField);
		userNameField.setColumns(10);

		passwordField = new JPasswordField();
		passwordField.setColumns(10);
		passwordField.setBounds(276, 131, 177, 20);
		add(passwordField);


		passwordAgainField = new JPasswordField();
		passwordAgainField.setColumns(10);
		passwordAgainField.setBounds(276, 164, 177, 20);
		add(passwordAgainField);


		JButton btnSend = new JButton("send");
		btnSend.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnSend.setBounds(396, 195, 57, 23);
		btnSend.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {

				if(passwordField.getText().equals(passwordAgainField.getText())){
					if ((userNameField.getText().length()>=5) && (userNameField.getText().length()<=30)) {
						ForumWorker<AInnerPanel> worker = new ForumWorker<AInnerPanel>(outerPanel.getConnection()){

						@Override
						protected AInnerPanel doInBackground() throws Exception {
							AInnerPanel returnedPanel = RegisterPanel.this;
							GUIAnswer registerAns = request(RequestType.REGISTER, new Object[] {userNameField.getText(),passwordField.getText()});
							outerPanel.setNumOfConnected(registerAns.getNumOfConnected());
							if((registerAns.getAnswerType().equals(AnswerType.ANSWER))&&((Boolean)registerAns.getArguments()[0])){
								GUIAnswer loginAns = request(RequestType.LOGIN, new Object[] {userNameField.getText(),passwordField.getText()});
								outerPanel.setNumOfConnected(loginAns.getNumOfConnected());
									if(loginAns.getAnswerType().equals(AnswerType.ANSWER)){
										outerPanel.changeSet(SetType.MEMBER);
									}
									else {
										returnedPanel = handleSendExceptions((Exception) loginAns.getArguments()[0]);
									}
							}
							else if(!(Boolean)registerAns.getArguments()[0]){
								JOptionPane.showMessageDialog(null, "you cannot register with that username (usename already taken)", "Registration Fail",JOptionPane.ERROR_MESSAGE);
							}
							else {
								returnedPanel = handleSendExceptions((Exception) registerAns.getArguments()[0]);
							}
							return returnedPanel;
						}

						@Override
						public void done(){
							try {
								outerPanel.swapInnerPanel(get());
							} catch (InterruptedException e) {
								outerPanel.swapInnerPanel(handleSendExceptions(e));
							} catch (ExecutionException e) {
								outerPanel.swapInnerPanel(handleSendExceptions(e));
							}
						}

						private AInnerPanel handleSendExceptions(Exception thrown){
							try {
								throw thrown;
							}catch (WrongPasswordException e) {
								JOptionPane.showMessageDialog(null, "Error occurred during automatic login. Please login manualy via the Login button", "Login Fail",JOptionPane.ERROR_MESSAGE);
								return requestHomePanel(outerPanel);
							} catch (WrongUserNameException e) {
								JOptionPane.showMessageDialog(null, "Error occurred during automatic login. Please login manualy via the Login button", "Login Fail",JOptionPane.ERROR_MESSAGE);
								return RegisterPanel.this;
							} catch (UnAuthorizedException e) {
								JOptionPane.showMessageDialog(null, "you are not authorized to register", "UnAuthorized use",JOptionPane.ERROR_MESSAGE);
								return RegisterPanel.this;
							} catch (SystemFailureException e) {
								JOptionPane.showMessageDialog(null, "system is unavalible at the moment, please try again later\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
								return requestHomePanel(outerPanel);
							} catch (Exception e) {
								JOptionPane.showMessageDialog(null, "operation failed! please try again\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
								return requestHomePanel(outerPanel);
							}
						}
					};
				worker.execute();
				}
				else {
					JOptionPane.showMessageDialog(null, "User name have to be 5 to 30 letters. Please try again");

				}
			}
			else{
				JOptionPane.showMessageDialog(null, "Password and Password again fields are not the same.\nPlease try again");
			}
		}});
		add(btnSend);
	}
}
